﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;

namespace Xceed.Silverlight.Data.Stats
{
  public class VarianceFunction : StatFunction
  {
    public VarianceFunction()
      : base()
    {
    }

    public VarianceFunction( string resultPropertyName, string sourcePropertyName )
      : base( resultPropertyName, sourcePropertyName )
    {
    }

    public VarianceFunction( string resultPropertyName, string sourcePropertyName, bool entirePopulation )
      : base( resultPropertyName, sourcePropertyName )
    {
      m_entirePopulation = entirePopulation;
    }

    #region EntirePopulation Property

    public bool EntirePopulation
    {
      get
      {
        return m_entirePopulation;
      }
      set
      {
        this.CheckSealed();
        m_entirePopulation = value;
      }
    }

    private bool m_entirePopulation = false;

    #endregion

    #region PrerequisiteFunctions Property

    protected internal override StatFunction[] PrerequisiteFunctions
    {
      get
      {
        StatFunction[] prerequisites = m_prerequisites;

        if( prerequisites == null )
        {
          prerequisites = new StatFunction[]
          {
            new AverageFunction( "VarianceFunction.Average", this.SourcePropertyName ),
            new CountFunction( "VarianceFunction.Count", this.SourcePropertyName )
          };

          if( this.IsSealed )
            m_prerequisites = prerequisites;
        }

        return prerequisites;
      }
    }

    #endregion

    protected internal override void InitializeFromInstance( StatFunction source )
    {
      base.InitializeFromInstance( source );

      this.EntirePopulation = ( ( VarianceFunction )source ).EntirePopulation;
    }

    protected internal override void Validate()
    {
      base.Validate();
      this.ValidateSourcePropertyName( 1 );
    }

    protected override void Initialize( Type[] sourcePropertyTypes )
    {
      base.Initialize( sourcePropertyTypes );

      switch( Type.GetTypeCode( sourcePropertyTypes[ 0 ] ) )
      {
        case TypeCode.Char:
        case TypeCode.Byte:
        case TypeCode.SByte:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
        case TypeCode.Single:
        case TypeCode.Double:
          m_accumulationType = TypeCode.Double;
          break;

        case TypeCode.Decimal:
          m_accumulationType = TypeCode.Decimal;
          break;
      }
    }

    protected internal override void Reset()
    {
      m_doubleSum = 0d;
      m_decimalSum = 0m;
      m_doubleAverage = 0d;
      m_decimalAverage = 0m;
      m_count = 0;
    }

    protected internal override void InitializePrerequisites( StatResult[] prerequisitesValues )
    {
      if( prerequisitesValues.Length != 2 )
        throw new ArgumentException( "The prerequisite initializers do not match the PrerequisiteFunctions." );

      switch( m_accumulationType )
      {
        case TypeCode.Double:
          m_doubleAverage = Convert.ToDouble( prerequisitesValues[ 0 ].Value );
          break;

        case TypeCode.Decimal:
          m_decimalAverage = Convert.ToDecimal( prerequisitesValues[ 0 ].Value );
          break;
      }

      m_count = Convert.ToInt64( prerequisitesValues[ 1 ].Value );

      if( !m_entirePopulation )
        m_count--;

      if( m_count <= 0 )
      {
        // No need to go further (i.e. Accumulate), the result cannot be calculated.
        throw new DivideByZeroException();
      }
    }

    protected internal override void Accumulate( object[] values )
    {
      if( StatFunction.CanProcessValues( values, 1 ) )
      {
        checked
        {
          switch( m_accumulationType )
          {
            case TypeCode.Double:
              {
                double diff = Convert.ToDouble( values[ 0 ] ) - m_doubleAverage;
                m_doubleSum += diff * diff;
              }
              break;

            case TypeCode.Decimal:
              {
                decimal diff = Convert.ToDecimal( values[ 0 ] ) - m_decimalAverage;
                m_decimalSum += diff * diff;
              }
              break;
          }
        }
      }
    }

    protected internal override StatResult GetResult()
    {
      object result = null;

      switch( m_accumulationType )
      {
        case TypeCode.Double:
          result = m_doubleSum / m_count;
          break;

        case TypeCode.Decimal:
          result = m_decimalSum / m_count;
          break;
      }

      return new StatResult( result );
    }

    protected internal override int GetEquivalenceKey()
    {
      return base.GetEquivalenceKey() ^ this.EntirePopulation.GetHashCode();
    }

    protected internal override bool IsEquivalent( StatFunction statFunction )
    {
      VarianceFunction varianceFunction = statFunction as VarianceFunction;

      if( varianceFunction == null )
        return false;

      if( varianceFunction.EntirePopulation != this.EntirePopulation )
        return false;

      return base.IsEquivalent( statFunction );
    }

    private TypeCode m_accumulationType = TypeCode.Empty;
    private double m_doubleSum;
    private decimal m_decimalSum;
    private double m_doubleAverage;
    private decimal m_decimalAverage;
    private long m_count;
    private StatFunction[] m_prerequisites;
  }
}
